<?php

namespace addons\sum\controller\performer;

use addons\sum\controller\Common;
use app\admin\model\sum\performer\Comment as CommentModel;
use app\admin\model\sum\performer\CommentLike as CommentLikeModel;
class Comment extends Common
{

    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];

    /**
     * 评价列表
     */
    public function index()
    {
        $user = auth_user();
        $list_rows = $this->request->param('list_rows', 10);
        $pid = $this->request->param('pid', 0);
        $performer_id = $this->request->param('performer_id');
        if(!$performer_id){
            $this->error(__('参数错误'));
        }
        $records=CommentModel::where('performer_id',$performer_id)->where('pid',$pid)->order('createtime DESC')->paginate($list_rows);
        $records->each(function ($item)use($user){
            $item['is_like']=0;
            if($user){
                $comment_like=CommentLikeModel::where('user_id',$user['id'])->where('comment_id',$item['id'])->find();
                if($comment_like){
                    $item['is_like']=1;
                }
            }
            $item['like_count']=CommentLikeModel::where('comment_id',$item['id'])->count();
            $item->hidden(['image']);
        });
        $this->success(__('获取成功'),$records);
    }

    /**
     * 发表|回复评论
     * @return void
     */
    public function create()
    {
        $user = auth_user();
        $pid = $this->request->param('pid', 0);
        $performer_id = $this->request->param('performer_id');
        if(!$performer_id){
            $this->error(__('参数错误'));
        }
        $content = $this->request->param('content');
        if(!$content){
            $this->error(__('参数错误'));
        }
        $image = $this->request->param('image','');
        $comment=new CommentModel();
        $comment->user_id=$user['id'];
        $comment->user_nickname=$user['nickname']??'';
        $comment->user_avatar=$user['avatar']??'';
        $comment->pid=$pid;
        $comment->performer_id=$performer_id;
        $comment->content=$content;
        $comment->image=$image;
        $comment->save();
        $this->success(__('操作成功'));
    }

    /**
     * 点赞|取消
     * @return void
     */
    public function like(){
        $user = auth_user();
        $comment_id = $this->request->param('comment_id');
        if(!$comment_id){
            $this->error(__('参数错误'));
        }
        $comment_like=CommentLikeModel::where('user_id',$user['id'])->where('comment_id',$comment_id)->find();
        if($comment_like){
            $comment_like->delete();
        }else{
            $comment_like=new CommentLikeModel();
            $comment_like->user_id=$user['id'];
            $comment_like->comment_id=$comment_id;
            $comment_like->save();
        }
        $this->success(__('操作成功'));
    }
}
